package com.sz.freemusic;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.GridView;

import com.sz.data.Artist;
import com.sz.freemusic.adapter.ArtistsListAdapter;
import com.sz.freemusic.common.ApplicationData;
import com.sz.freemusic.net.HttpRetreiver;
import com.sz.freemusic.net.RequestBuilder;
import com.sz.freemusic.net.RequestQueue;

public class MainActivity extends Activity {

	private GridView artistList;
	private ArtistsListAdapter artistListAdapter;
	protected int page = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		artistList = (GridView) findViewById(R.id.artist_grid);
		artistListAdapter = new ArtistsListAdapter(this);
		artistList.setAdapter(artistListAdapter);
		ApplicationData.getInstance().setContext(this);
		ApplicationData.getInstance().initBitmapCache();
		artistList.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (!artistListAdapter.isEmpty()) {
					if (++firstVisibleItem + visibleItemCount > totalItemCount) {
						testHttp(page++);
					}
				}
				
			}
		});
		testHttp(page);
		
	}
	
	
	private void testHttp(final int page) {
		RequestQueue.getInstance().enqueueRequest(new Runnable() {
			
			@Override
			public void run() {
				final ArrayList<Artist> artists = HttpRetreiver.connect(new RequestBuilder().getArtistListsRequest(page));
				MainActivity.this.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						for (Artist artist:artists) {
							artistListAdapter.add(artist);
						}
						
					}
				});
			}
		});
		
			
				

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}
	
	

}
